var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

// 引入接口文件
var uploadApi = require('./api/upload');
var userApi = require('./api/user');
var productApi = require('./api/product');
var bannerApi = require('./api/banner');
var specyApi = require('./api/specy');
var reasonApi = require('./api/reason');
var categoryApi = require('./api/category');
var commentApi = require('./api/comment');
var addressApi = require('./api/address');
var cartApi = require('./api/cart');
var orderApi = require('./api/order');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 配置跨域选项，只允许这一个域的跨域
const corsOptions = {
  origin: 'http://192.168.11.107:8080',
  optionsSuccessStatus: 200
}

// 当前项目的所有接口都允许跨域
app.use(cors())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// 注册接口
app.use('/api/upload', uploadApi);
app.use('/api/user', userApi);
app.use('/api/product', productApi);
app.use('/api/banner', bannerApi);
app.use('/api/specy', specyApi);
app.use('/api/reason', reasonApi);
app.use('/api/category', categoryApi);
app.use('/api/comment', commentApi);
app.use('/api/address', addressApi);
app.use('/api/cart', cartApi);
app.use('/api/order', orderApi);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
